import React from 'react';
import { Link as ReactLink, useHistory } from 'react-router-dom'

import Stack from '@material-ui/core/Stack';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Paper from '@material-ui/core/Paper';
import Box from '@material-ui/core/Box';
import Grid from '@material-ui/core/Grid';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import Snackbar from '@material-ui/core/Snackbar';
import MuiAlert from '@material-ui/core/Alert';
import { createTheme, ThemeProvider } from '@material-ui/core/styles';

import { request } from '../../request';

//作者介绍
function Copyright(props) {
    return (
        <Typography variant="body2" color="text.secondary" align="center" {...props}>
            {'Copyright © '}
            <Link color="inherit">
                暴龙战士小组
            </Link>{' '}
            {new Date().getFullYear()}
        </Typography>
    );
}

//主题
const theme = createTheme();

//Alert封装
const Alert = React.forwardRef(function Alert(props, ref) {
    return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});

export default function SignInSide() {

    //设置两个state变量
    const [open, setOpen] = React.useState(false);
    const [msg, setMsg] = React.useState(null);
    const history = useHistory();

    const handleClose = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }
        setOpen(false);
    };

    //由于网络请求是异步的，不论将setOpen写在何处，都会出现提示信息出现的情况，那是因为
    //一旦触发click或submit事件，网络请求返回的msg总是慢于setOpen的速度，于是会出现第一次
    //点击无反应（网络请求结果未返回，setOpen为false），第二次点击出现提醒，是因为其使用的是
    //第一次的msg,第三次使用的是第二次的msg(即为null).
    // if(msg !== null) {
    //   setOpen(true);
    //   setMsg(null);
    // }else setOpen(false);


    const handleSubmit = (event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        const login = {
            account: data.get('account'),
            password: data.get('password'),
        }

        //发送请求
        request({
            url: '/user/login',
            method: 'POST',
            data: login
        }).then(res => {
            if (res instanceof Object) {
                //如果后端返回了Token,将其保存到sessionStorage中
                setOpen(false);
                sessionStorage.setItem("token", res.data);
                history.replace('/index');
            } else {
                setMsg(res);
                setOpen(true);
            }

        })

    }

    return (
        <ThemeProvider theme={theme}>
            <Grid container component="main" sx={{ height: '100vh' }}>
                <CssBaseline />
                <Grid
                    item
                    xs={false}
                    sm={4}
                    md={7}
                    sx={{
                        backgroundImage: 'url(https://source.unsplash.com/random)',
                        backgroundRepeat: 'no-repeat',
                        backgroundColor: (t) =>
                            t.palette.mode === 'light' ? t.palette.grey[50] : t.palette.grey[900],
                        backgroundSize: 'cover',
                        backgroundPosition: 'center',
                    }}
                />
                <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
                    <Box
                        sx={{
                            my: 8,
                            mx: 4,
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                        }}
                    >
                        <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
                            <LockOutlinedIcon />
                        </Avatar>
                        <Typography component="h1" variant="h5">
                            Sign in
                        </Typography>
                        <Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 1 }}>
                            <TextField
                                margin="normal"
                                required
                                fullWidth
                                id="account"
                                label="账号"
                                name="account"
                                autoComplete="account"
                                autoFocus
                            />
                            <TextField
                                margin="normal"
                                required
                                fullWidth
                                name="password"
                                label="密码"
                                type="password"
                                id="password"
                                autoComplete="current-password"
                            />
                            <FormControlLabel
                                control={<Checkbox value="remember" color="primary" />}
                                label="Remember me"
                            />
                            <Button
                                type="submit"
                                fullWidth
                                variant="contained"
                                sx={{ mt: 3, mb: 2 }}
                            >
                                登 录
                            </Button>

                            {/* 消息提醒 */}
                            <Stack spacing={2} sx={{ width: '100%' }}>
                                <Snackbar
                                    anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
                                    open={open}
                                    autoHideDuration={3000}
                                    onClose={handleClose}
                                >
                                    <Alert onClose={handleClose} severity="error" sx={{ width: '100%' }}>
                                        {msg}
                                    </Alert>
                                </Snackbar>
                            </Stack>

                            <Grid container>
                                <Grid item>
                                    <ReactLink to="/register">{"没有账号? 请注册"}</ReactLink>
                                </Grid>
                            </Grid>
                            <Copyright sx={{ mt: 5 }} />
                        </Box>
                    </Box>
                </Grid>
            </Grid>
        </ThemeProvider>
    );
}
